/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/29 22:57
 */
package org.mechanic.fund.service.wechat.impl;

import org.mechanic.core.Constants;
import org.mechanic.fund.domain.wechat.WcBaseInfo;
import org.mechanic.fund.repository.wechat.BaseInfoRepository;
import org.mechanic.fund.service.wechat.IWcBaseInfoService;
import org.mechanic.utils.text.EncodeUtil;
import org.mechanic.utils.text.HashUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 微信公众平台基础信息相关服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class WcBaseInfoService implements IWcBaseInfoService {
    private final BaseInfoRepository baseInfoRepository;

    @Autowired
    public WcBaseInfoService(BaseInfoRepository baseInfoRepository) {this.baseInfoRepository = baseInfoRepository;}

    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public WcBaseInfo findById(String id) {
        return this.baseInfoRepository.findOne(id);
    }

    /**
     * 返回匹配类型的公众平台基础信息
     *
     * @param type 主键编号
     * @return 公众平台基础信息
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public List<WcBaseInfo> findByType(Integer type) {
        return this.baseInfoRepository.findByType(type);
    }

    /**
     * 返回所有公众平台基础信息列表
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public List<WcBaseInfo> getList() {
        return (List<WcBaseInfo>) this.baseInfoRepository.findAll();
    }



    /**
     * 服务号签名验证
     * @param signature 微信加密签名。signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 验证是否成功
     */
    @Override
    public boolean isSignature(String signature, String timestamp, String nonce) {

        String[] arr = {Constants.MP_TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }

        String encrpt = EncodeUtil.encodeHex(HashUtil.sha1(sb.toString()));

        // 确认请求来至微信
        return encrpt.equalsIgnoreCase(signature);
    }
}
